import { defineStore } from 'pinia'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, getInfo, logout } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			nickname: storage.get(constant.nickname),
			avatar: storage.get(constant.avatar)
		}
	},
	getters: {
		
	},
	actions: {
		loginAction(data) {
			return new Promise((resolve, reject) => {
				login(data).then(res => {
					setToken(res.result)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		getInfoAction() {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					let result = res.result || {}
					let user = result.userVO || {}
					this.nickname = user.nickname ? user.nickname : ""
					this.avatar = user.userFile && user.userFile[0] ? user.userFile[0] : null
					
					storage.set(constant.nickname, this.nickname)
					storage.set(constant.avatar, this.avatar)
					resolve(res.result)
				}).catch(error => {
					reject(error)
				})
			})
		},
		logOutAction() {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					removeToken()
					storage.clean()
					this.nickname = ''
					this.avatar = ''
					
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
})